<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var largestMultipleOfThree = function (digits) {
      const sum = digits.reduce((pre, num) => pre + num, 0);
      if (sum === 0) return '0';
      if (sum % 3 === 0) return digits.sort((a, b) => b - a).join('');

      const temp = digits.reduce((pre, num) => {
        pre[num % 3].push(num);
        return pre;
      }, [[], [], []]);

      const res = (nums, n = 1) => {
        nums.sort((a, b) => b - a);
        while (n > 0) {
          nums.pop();
          n--;
        }
        const r = [...temp[0], ...temp[1], ...temp[2]].sort((a, b) => b - a).join('');
        if (r.length > 0 && r[0] === '0') return '0';
        return r;
      };

      if (sum % 3 === 1) {
        if (temp[1].length) return res(temp[1]);
        if (temp[2].length > 1) return res(temp[2], 2);
      }

      if (temp[2].length) return res(temp[2]);
      if (temp[1].length > 1) return res(temp[1], 2);
      return '';
    }
    console.log(largestMultipleOfThree([8, 1, 9]));
  </script>
</body>

</html>